package services

import (
	"os/exec"
	"os"
	"log"
	"fmt"
	"bytes"

	"huaxrobot/models"
)

func Runshell(planid string) {
	os.Chdir("../../huaxtest_ui") 

	command := "pwd"
	cmd := exec.Command("/bin/bash", "-c", command)
	log.Println(command)
	bytes1,err := cmd.Output()
	if err != nil {
		 log.Println(err)
	}
	resp := string(bytes1)
	log.Println(resp)


	command = "whoami"
	log.Println(command)
	cmd = exec.Command("/bin/bash", "-c", command)
	bytes1,err = cmd.Output()
	if err != nil {
		 log.Println(err)
	}
	resp = string(bytes1)
	log.Println(resp)

	//command = "chmod +x ./scripts/build_docker.sh"
	command = "chmod +x ./scripts/runpytest.sh"
	log.Println(command)
	cmd = exec.Command("/bin/bash", "-c", command)
	bytes1,err = cmd.Output()
	if err != nil {
		 log.Println(err)
	}
	resp = string(bytes1)
	log.Println(resp)

	command = "./scripts/runpytest.sh " + planid
	log.Println(command)
	cmd = exec.Command("/bin/bash", "-c", command)
	var out bytes.Buffer
	var stderr bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &stderr
	err = cmd.Run()
	if err != nil {
		fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
		return
	}
	fmt.Println("Result: " + out.String())
	
	//写数据库状态位
	plan := models.PlanCase{}
	plan.UpdateStatus(planid)
}
